package com.handpay.zztong.hp.login.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.db.ormlite.DataBaseComponentModel;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.component.ComponentConfigUtil;
import com.handpay.zztong.hp.main.model.component.ComponentItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentMappingItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentRelationItemBean;
import com.handpay.zztong.hp.utils.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

public class WelcomeActivity extends ZZTongActivity {
    private Long mTime;
    private AlertDialog mDialog;
    private boolean isTestUrl = true;

    @Override
    public boolean isListenerVoice() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_welcome);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        super.onCreate(savedInstanceState);
        mTime = SystemClock.elapsedRealtime();
        mIsMainPage = true;
        if (chekUserTimeout != null) {
            chekUserTimeout.clearTime();//清除用户操作超时时间
        }
        //启动友盟统计相关
        MobclickAgent.UMAnalyticsConfig umAnalyticsConfig = new MobclickAgent.UMAnalyticsConfig(this, ZZTConfig.UMENG_APPKEY, ZZTConfig.UPDATE_CHANNEL, MobclickAgent.EScenarioType.E_UM_NORMAL, false);
        MobclickAgent.startWithConfigure(umAnalyticsConfig);
        DataBaseComponentModel dbModel = new DataBaseComponentModel(this);

        //初始化组件数据库
        if (dbModel.queryComponentMappingList() == null || dbModel.queryComponentMappingList().size() == 0) {
            List<ComponentRelationItemBean> dbComponentRelationList = dbModel.queryComponentRelationList();
            if (dbComponentRelationList == null || dbComponentRelationList.size() == 0) {
                ArrayList<ComponentRelationItemBean> componentRelationList = ComponentConfigUtil.getComponentRelationListFromConfig(this);
                for (ComponentRelationItemBean bean : componentRelationList) {
                    dbModel.addComponentRelation(bean);
                }
            }

            List<ComponentMappingItemBean> dbComponentMappingList = dbModel.queryComponentMappingList();
            if (dbComponentMappingList == null || dbComponentMappingList.size() == 0) {
                ArrayList<ComponentMappingItemBean> componentMappingList = ComponentConfigUtil.getComponentMappingListFromConfig(this);
                for (ComponentMappingItemBean bean : componentMappingList) {
                    dbModel.addComponentMapping(bean);
                }
            }

            List<ComponentItemBean> dbComponentList = dbModel.queryComponentList();
            if (dbComponentList == null || dbComponentList.size() == 0) {
                ArrayList<ComponentItemBean> componentList = ComponentConfigUtil.getComponentListFromConfig(this);
                for (ComponentItemBean bean : componentList) {
                    dbModel.addComponent(bean);
                }
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onResume() {
        super.onResume();
//        SecureManager.getInstance().CheckDesKey();
        ClientEngine.getInstance().saveGlobal(ZZTongActivity.VerifyVersionOK, false);
        if (ZZTConfig.ENV.CANSET) {
            if (mDialog != null && mDialog.isShowing()) {
                return;
            }
            AlertDialog.Builder mAlertBuilder = new AlertDialog.Builder(this, R.style.Theme_CustomDialog);
            LayoutInflater mLayoutInflater = LayoutInflater.from(this);
            View content = mLayoutInflater.inflate(R.layout.setting, null);
            final EditText etDomain = (EditText) content.findViewById(R.id.et_domain);
            final EditText etDomains = (EditText) content.findViewById(R.id.et_domains);
            String urls = ZZTConfig.ENV.SERVER;
            if (isTestUrl) {
                etDomain.setHint(urls.substring(0, urls.lastIndexOf(".") + 1));
                etDomains.setHint(urls.substring(urls.lastIndexOf(".") + 1));
                etDomains.setVisibility(View.VISIBLE);
            } else {
                etDomains.setVisibility(View.GONE);
                etDomain.setHint(urls);
            }

            final EditText etPort = (EditText) content.findViewById(R.id.et_port);
            etPort.setHint(String.valueOf(ZZTConfig.ENV.PORT));
            final EditText etCsn = (EditText) content.findViewById(R.id.et_csn);
            if (ZZTConfig.ENV.SWIPERCSN) {
                etCsn.setEnabled(false);
                etCsn.setHint(R.string.welcome_hint);
            } else {
                etCsn.setHint(ZZTConfig.ENV.CSN);
            }
            final EditText etChannel = (EditText) content.findViewById(R.id.et_channel);
            etChannel.setHint(ZZTConfig.ENV.CHAN);

            final EditText etClientVersion = (EditText) content.findViewById(R.id.et_clientVersion);
            etClientVersion.setHint(ClientEngine.VERSION);

            final EditText etClientChannel = (EditText) content.findViewById(R.id.et_clientchannel);
            etClientChannel.setHint(ZZTConfig.UPDATE_CHANNEL);

            mAlertBuilder.setView(content);
            mAlertBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String domain1 = etDomain.getText().toString();
                    String domain = domain1;
                    if (isTestUrl) {
                        if (TextUtils.isEmpty(domain1)) {
                            domain1 = etDomain.getHint().toString();
                        }
                        String domain2 = etDomains.getText().toString();
                        if (TextUtils.isEmpty(domain2)) {
                            domain2 = etDomains.getHint().toString();
                        }
                        domain = domain1 + domain2;
                    }
                    if (TextUtils.isEmpty(domain)) {
                        domain = ZZTConfig.ENV.SERVER;
                    }
                    if (TextUtils.isEmpty(domain)) {
                        domain = etDomain.getHint().toString();
                    }
                    String port = etPort.getText().toString();
                    if (TextUtils.isEmpty(port)) {
                        port = etPort.getHint().toString();
                    }
                    String csn = etCsn.getText().toString();
                    if (TextUtils.isEmpty(csn)) {
                        csn = etCsn.getHint().toString();
                    }
                    String channel = etChannel.getText().toString();
                    if (TextUtils.isEmpty(channel)) {
                        channel = etChannel.getHint().toString();
                    }
                    String clientVersion = etClientVersion.getText().toString();
                    if (TextUtils.isEmpty(clientVersion)) {
                        clientVersion = etClientVersion.getHint().toString();
                    }
                    String clientchannel = etClientChannel.getText().toString();
                    if (TextUtils.isEmpty(clientchannel)) {
                        clientchannel = etClientChannel.getHint().toString();
                    }
                    ClientEngine.VERSION = clientVersion;
                    HPLog.d("activity_welcome", "ClientEngine.VERSION" + ClientEngine.VERSION);
                    ZZTConfig.UPDATE_CHANNEL = clientchannel;
                    if (ZZTConfig.isUseHTTPS) {
                        ClientEngine.getInstance().init(WelcomeActivity.this.getApplicationContext(), ZZTConfig.ENV.HPV, "https://" + domain.trim() + "/" + ZZTConfig.URL_PATH, channel);
                    } else {
                        ClientEngine.getInstance().init(WelcomeActivity.this.getApplicationContext(), ZZTConfig.ENV.HPV, "http://" + domain.trim() + ":" + port.trim() + "/" + ZZTConfig.URL_PATH, channel);
                    }
                    ZZTConfig.testerCsn = csn;
                    doVerifyVersion(WelcomeActivity.this);
                }
            });
            mAlertBuilder.setCancelable(false);
            mDialog = mAlertBuilder.create();
            mDialog.show();
        } else {
            if (ZZTConfig.isUseHTTPS) {
                ClientEngine.getInstance().init(this, ZZTConfig.ENV.HPV, "https://" + ZZTConfig.ENV.SERVER.trim() + "/" + ZZTConfig.URL_PATH, ZZTConfig.ENV.CHAN);
            } else {
                ClientEngine.getInstance().init(this, ZZTConfig.ENV.HPV, "http://" + ZZTConfig.ENV.SERVER.trim() + ":" + ZZTConfig.ENV.PORT + "/" + ZZTConfig.URL_PATH, ZZTConfig.ENV.CHAN);
            }
            doVerifyVersion(WelcomeActivity.this);
        }

    }


    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        boolean result = super.netJsonResponse(action, resp, showAlert);
        String isVersion = (String) ClientEngine.getInstance().getGlobal(VERSION);
        if (result && !TextUtils.isEmpty(isVersion)) {
            gotoLogin();
        }
        return true;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        boolean result = super.netResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                WelcomeActivity.this.finish();
            }
        });
        // 是否有能取到版本号，如果isVersion是null 则不到登陆界面
        String isVersion = (String) ClientEngine.getInstance().getGlobal(VERSION);
        if (result && !TextUtils.isEmpty(isVersion)) {
            gotoLogin();
            return true;
        }
        return true;
    }


    /***
     * 登录操作
     */
    public void gotoLogin() {
        long time = SystemClock.elapsedRealtime();
        if ((time - mTime) <= ZZTConstant.WELCOME_TIME) {
            this.getWindow().getDecorView().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
                    finish();
                }
            }, ZZTConstant.WELCOME_TIME - (time - mTime));
        } else {
            this.startActivity(new Intent(this, LoginActivity.class));
            this.finish();
        }
    }

    protected boolean isShownTopBar() {
        return false;
    }

    protected boolean isShownTabs() {
        return false;
    }
    @Override
    public void setStatusBar() {
        StatusBarUtil.setTranslucentForImageView(this, 0, null);
    }
}